#include "aliyun_model.h"
#include "aliyun_core.h"
#include "app_debug.h"
#include "FreeRTOS.h"
#include "task.h"
#include "timers.h"




TimerHandle_t timer_test;
static bool is_inited=false;
static bool if_ali_online=false;

void model_test_timer_hanlder( TimerHandle_t xTimer )
{
    model_report_alarm(1,true,1000);
}

void model_state_handler(ali_state_e state)
{
    
    if(state==ALI_STATE_OFFLINE)
    {
        if_ali_online=false;
        DEBUG("model state is offline",state);
    }
    else if(state==ALI_STATE_ONLINE)
    {
        if(if_ali_online==false)     //Switch from offline to online
        {
            if_ali_online=true;
            DEBUG("model state is online",state);
            //TODO  report all property
            //ali_pub_data_flush();
        }
        
    }
    
}

bool model_init()
{
    ali_state_register(model_state_handler);
    timer_test=xTimerCreate("test_timer",1000*60*10,pdTRUE,NULL,model_test_timer_hanlder);
    xTimerStart(timer_test,2000);
    is_inited=true;
    model_report_alarm(1,true,1000);  //for test
    return true;
}


bool model_report_online(uint8_t dev_num,bool is_online)
{
    uint8_t data[2];
    if(is_inited==false)return false;
    if(ali_state_get()==ALI_STATE_OFFLINE)
    {
        return false;
    }
    data[0]=MODEL_PROPERTY_ONLINE+dev_num;
    data[1]=is_online;
    return ali_pub_data_queue(ALI_MODEL_PROP_REPORT,GET_ID,data,2,1000);
}

bool model_report_alarm(uint8_t dev_num,bool is_alarm,uint32_t timeout)
{
    uint8_t data[2];
    if(is_inited==false)return false;
    data[0]=MODEL_PROPERTY_ALARM+dev_num;
    data[1]=is_alarm;
    return ali_pub_data_queue(ALI_MODEL_PROP_REPORT,GET_ID,data,2,timeout);
}

bool model_report_bat(uint8_t dev_num,uint8_t bat)
{
    uint8_t data[2];
    if(is_inited==false)return false;
    if(ali_state_get()==ALI_STATE_OFFLINE)
    {
        return false;
    }
    data[0]=MODEL_PROPERTY_BAT+dev_num;
    data[1]=bat;
    return ali_pub_data_queue(ALI_MODEL_PROP_REPORT,GET_ID,data,2,1000);   
}
